package cn.tsingyu.antsclub.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.tsingyu.antsclub.annotation.RequiresPermissions;

public class PermissionInterceptor extends HandlerInterceptorAdapter {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            RequiresPermissions requiresPermissions = ((HandlerMethod) handler).getMethodAnnotation(RequiresPermissions.class);
            
            //没有声明需要权限,或者声明不验证权限
            if(requiresPermissions == null || requiresPermissions.value().length==0){
                return true;
            }else{  
            	String[] permissions = requiresPermissions.value();
            	System.out.println(permissions);
                //在这里实现自己的权限验证逻辑
                if(false)//如果验证成功返回true（这里直接写false来模拟验证失败的处理）
                    return true;
                else//如果验证失败
                {
                    //返回到登录界面
//                	request.setAttribute("msg", "权限不足，无法访问");
                	request.getSession().setAttribute("msg", "权限不足，无法访问");
                    response.sendRedirect("/msg");
//                    PrintWriter out = response.getWriter();  
//                    out.print("权限不足，无法访问");  
                    return false;
                }       
            }
        }
        else
            return true;   
     }
}